package com.landmark;

import java.io.File;
import javax.swing.JPanel;

public class RenameDirFiles extends JPanel {

    String strFolder = "";
    String strPrefix = "";
    String strSuffix = "";
    String strRemPrefix = "";
    String strRemSuffix = "";

    public void start() {
        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String folderPath = strFolder;
        String renameExt = strSuffix;
        String prefix = strPrefix;
        String remPrefix = strRemPrefix;
        String remSuffix = strRemSuffix;
        String[] dir = new java.io.File(folderPath).list();
        java.util.Arrays.sort(dir);
        File f[] = new File(folderPath).listFiles();
        int len1 = dir.length;
        int thumbNailCount = 0;
        for (int i = 0; i < len1; i++) {
            String name = f[i].getName();
            if (remPrefix.trim().length() != 0) {
                String prefixStr = name.substring(0,remPrefix.length());
                if( prefixStr.equalsIgnoreCase(remPrefix))
                    name = name.substring(remPrefix.length());                
            }
            if(remSuffix.trim().length() !=0 ) {
                int suffixIndex = name.indexOf(remSuffix);
                name = name.substring(0,suffixIndex) + name.substring(name.lastIndexOf("."), name.length()) ;
            }
            
            int j = name.lastIndexOf('.');
            int lastUnderScore = name.lastIndexOf('_');
            // If extension not given then use the original extension 
            // Ex: input=Sample_SW.jpg and 
            // extension given as LG output=Sample_LG.jpg 
            // else output=Sample_SW.jpg 

            if (renameExt.trim().length() == 0) {
                renameExt = name.substring(lastUnderScore, j);
            }
            if (lastUnderScore == -1) {
                lastUnderScore = j;
            }
            // Will Convert the file with Sample_Main.jpg 
            // to Sample_LG.jpg ( If prefix is not given) 
            // else Prefix_Sample_LG.jpg
            if ((!name.substring(j + 1, name.length()).equalsIgnoreCase("db"))) {
                String newName = name.substring(0, j) + renameExt + name.substring(j, name.length());
                // Add prefix to newname
                if (prefix.trim().length() > 0) {
                    newName = prefix + "_" + newName;
                }
                File newFileName = new File(f[i].getParentFile(), newName);
                f[i].renameTo(newFileName);
            } else {
                thumbNailCount++;
            }
        }
        System.out.println("Total files converted : " + (len1 - thumbNailCount));
    }
}